package util

import (
	"gove/core"
	"time"

	"github.com/mojocn/base64Captcha"
)

var CaptchaUtil = captchaUtil{300}

type captchaUtil struct {
	captchaExpire int // 验证码过期时间,分钟为单位
}

func (cu *captchaUtil) Generate() (string, string, error) {
	driver := base64Captcha.NewDriverDigit(80, 240, 4, 0.7, 80)
	store := base64Captcha.NewMemoryStore(100, time.Duration(cu.captchaExpire)*time.Minute)
	c := base64Captcha.NewCaptcha(driver, store)

	id, imgBytes, answer, err := c.Generate()
	if err != nil {
		return "", "", err
	}

	// 使用结构体方法直接操作Redis
	result := RedisUtil.Set(id, answer, cu.captchaExpire)
	if !result {
		core.Logger.Errorf("redisUtil.Set err: err=[%+v]", result)
	}
	return id, imgBytes, nil
}

func (cu *captchaUtil) Verify(id, answer string) bool {
	if id == "" || answer == "" {
		return false
	}
	value := RedisUtil.Get(id)
	return value == answer
}
